package org.jiucheng.magpiebridge.manager;

import java.net.InetSocketAddress;
import java.text.MessageFormat;
import java.util.EnumSet;

import javax.servlet.DispatcherType;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.jiucheng.magpiebridge.util.Cfg;
import org.jiucheng.web.filter.CharacterEncodingFilter;
import org.jiucheng.web.filter.DispatcherFilter;

/**
 * 
 * @author jiucheng
 *
 */
public class Manager {
    
    public static void main(String[] args) throws Exception {
        Cfg.buildBaseDir(Manager.class);
        Cfg.loadProperties();
        
        Server server = new Server(new InetSocketAddress(Cfg.getServerIp(), Cfg.getServerPort()));
        
        ServletContextHandler context = new ServletContextHandler();
        context.setContextPath("/");
        // 静态资源
        context.setResourceBase(MessageFormat.format("{0}webapp", Cfg.baseDir()));
        context.addServlet(new ServletHolder(new DefaultServlet()), "/*");
        
        ServletHandler servletHandler = new ServletHandler();
        // 编码
        FilterHolder charsetFilter = servletHandler.addFilterWithMapping(CharacterEncodingFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
        charsetFilter.setInitParameter("encoding", "UTF-8");
        context.addFilter(charsetFilter, "/*", EnumSet.allOf(DispatcherType.class));
        // 路由
        FilterHolder dispatcherFilterHolder = servletHandler.addFilterWithMapping(DispatcherFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
        dispatcherFilterHolder.setInitParameter("cfg", MessageFormat.format("{0}conf/cfg.properties", Cfg.baseDir()));
        context.addFilter(dispatcherFilterHolder, "/*", EnumSet.allOf(DispatcherType.class));
        
        server.setHandler(context);
        server.start();
    }
}
